package com.ruoyi.core.config.mp;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.core.config.utils.WxUtil;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * 微信公众号登录
 */
@RequestMapping("core/gzh")
@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
public class WxMpLoginController extends BaseController {
    private final WxMpService wxMpService;
    private final IUserService iUserService;

    @SaIgnore
    @GetMapping("login")
    public R<LoginVo> login(@NotBlank(message = "code不能为空") String code) {
        //通过缓存 判断用户
        UserVo userVo = WxUtil.getUserVoByToken();
        if (ObjectUtil.isNotNull(userVo)) {
            //刷新缓存，
            WxUtil.refreshWxUser(userVo, false);
            return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo ,"0"));
        }
        // 获取用户数据
        WxOAuth2UserInfo userInfo = getUserInfo(code);
        userVo = iUserService.getByOpenId(userInfo.getOpenid());
        if(ObjectUtil.isNull(userVo)){
            //保存用户数据
            userVo = iUserService.setWxUser(userInfo.getUnionId(), userInfo.getOpenid(), "0",userInfo.getNickname(), userInfo.getHeadImgUrl());
            // 执行登录操作
            WxUtil.refreshWxUser(userVo,true);

            return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(), userVo ,"1"));
        }
        // 刷新缓存
        WxUtil.refreshWxUser(userVo,true);
        return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo ,"0"));
    }

    private WxOAuth2UserInfo getUserInfo(String code){
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            return wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取用户信息
     */
    @GetMapping("getUser")
    public R<UserVo> getUser() {
        return R.ok(WxUtil.getUserVoByToken());
    }
}
